package cn.vcjf.washcar.common.util.weixin;

import cn.vcjf.washcar.common.util.httpUtils.HttpClientUtils;
import cn.vcjf.washcar.dict.entity.Dict;
import cn.vcjf.washcar.dict.service.DictCache;
import cn.vcjf.washcar.dict.service.IDictService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Auther: zhengzihang
 * @Date: 2018/7/31 16:35
 * @Description:
 */
@Service
public class AbstractWxPayAuthImpl extends AbstractWxPayAuth {
	private Logger logger = LoggerFactory.getLogger(this.getClass());


	@Resource
	protected IDictService dictService;

	//	@Value("${manager.openid}")
	protected String managerOpenId = "MANAGER_OPENID";


	@Override
	protected String getUnifiedOrderUrl() {
		return null;
	}

	@Override
	protected String getThisServletUrl() {
		return "vc-washcar-manager/updateManagerQrCode.do";
	}

	@Override
	protected void doSuccess(String openId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		try {
			logger.info("获取微信公众号openId : {} ----开始绑定.............", openId);
			logger.info("===============绑定微信号开始===================");
			Dict dict = new Dict();
			dict.setValue(openId);
			dict.setType(managerOpenId);

			boolean update = dictService.updateOpenId(dict);
			String res = "绑定微信号成功!";
			if (update) {
				//  清空缓存
				DictCache.clear();
				logger.info("===============绑定微信号成功===================");
				try{
					String url = "https://m.vc-group.cn/wash-car-api/order/washCarOrder/cleanOpenId";
					System.out.println(url);
					HttpPost post = new HttpPost(url);
					HttpClient c = HttpClientUtils.getConnection();
					HttpResponse httpResponse = c.execute(post);
					logger.info("===============清理绑定微信号成功===================");
				}catch(Exception e){
					logger.info("===============清理绑定微信号失败===================");
					e.printStackTrace();
				}
			} else {
				res = "绑定微信号失败!";
				logger.info("===============绑定微信号失败===================");
			}
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print("<script type='text/javascript'>");
			out.print("WeixinJSBridge.invoke('closeWindow');");
			out.print("</script>");
			return;
		} catch (Exception e) {
			logger.error("微信公众号请求异常:{}", e);
			response.getWriter().print("绑定微信号失败");
		}
		return;
	}

	@Override
	protected void doCheckRequestParams(HttpServletRequest request) {

	}
}
